package com.jl.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jl.commons.base.BaseController;
import com.jl.commons.constant.Constants;
import com.jl.commons.constant.ErrorCode;
import com.jl.commons.constant.ErrorMessage;
import com.jl.commons.result.PageDataInfo;
import com.jl.commons.result.ResultData;
import com.jl.commons.shiro.ShiroUser;
import com.jl.commons.utils.BASE64;
import com.jl.model.Menu;
import com.jl.service.IMenuService;
import com.jl.service.IRoleService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author 江剑
 */
@Controller
@RequestMapping("/menu")
public class MenuController extends BaseController {

    @Autowired
    private IMenuService menuService;

    @Autowired
    private IRoleService roleService;

    @PostMapping("/ignTree")
    @ResponseBody
    public ResultData menueTree() {
        ShiroUser shiroUser = getShiroUser();
        if (null != shiroUser) {
            List<Menu> allMenus = new ArrayList<>();
            List<Long> rolesList = shiroUser.getRoleIds();

            if (rolesList != null && !rolesList.isEmpty()) {
                for (Long roleId : rolesList) {
                    List<Menu> tempMenus = menuService.selectMenuByRoleId(roleId);
                    // 只取菜单和目录，过滤功能
                    Stream<Menu> stream = tempMenus.stream().filter(menu -> (menu.getType() == 0 || menu.getType() == 1 || allMenus.contains(menu)));
                    allMenus.addAll(stream.collect(Collectors.toList()));
                }
            }
            //按照orderby排序
            allMenus.sort((m1, m2) -> m1.getOrderby().compareTo(m2.getOrderby()));
            // 获取父节点为0的根节点
            List<Menu> rootMenus = menuService.getRootMenuList(allMenus);
            Map<String,Object> map =new HashMap<String,Object>();
            for(Menu rootMenu : rootMenus){
                List<Menu> childMenus = menuService.getchildMenus(allMenus, rootMenu.getId());
                rootMenu.setChildren(childMenus);
            }
            map.put("root",rootMenus);
            return success(map);

        }

        return fail();
    }


    @GetMapping("/menuDataGrid")
    @RequiresPermissions("/menu/menuDataGrid")
    public String menuList(){
        return "menu_list";
    }


    @GetMapping("/add")
    @RequiresPermissions("/menu/add")
    public String menuPage(ModelMap mp, Long id){
        mp.put("id",id);
        return "menu_add";
    }

    @PostMapping("/add")
    @RequiresPermissions("/menu/add")
    @ResponseBody
    public ResultData addMenu(String json){
        String value = BASE64.decode(json);
        if(null == value){
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        Menu menu = JSON.parseObject(value,Menu.class);
        //新增数据
        menu.setCreateId(getUserId());
        menu.setGmtCreate(new Date());

        menuService.save(menu);
        return success(menu);
    }

    @GetMapping("/edit")
    @RequiresPermissions("/menu/edit")
    public String editMenuPage(ModelMap mp,Long id){
        mp.put("id",id);
        return "menu_add";
    }

    @PostMapping("/edit")
    @RequiresPermissions("/menu/edit")
    @ResponseBody
    public ResultData editMenu(String json){
        String value = BASE64.decode(json);
        if(null == value){
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        Menu menu = JSON.parseObject(value,Menu.class);
        menu.setGmtModified(new Date());
        menu.setModifyId(getUserId());
        menuService.updateById(menu);
        return success(menu);
    }


    @PostMapping("/delete")
    @RequiresPermissions("/menu/delete")
    @ResponseBody
    public ResultData deletesMenu(String json){
        String value = BASE64.decode(json);
        if(null == value){
            return fail(ErrorCode.BASE64_DECODER_ERROR, ErrorMessage.BASE64_DECODER_ERROR);
        }
        List<Long> ids = JSONArray.parseArray(value,Long.class);
        boolean b = menuService.deleteMenuByIds(ids);
        if(b){
            return success();
        }
        return fail();
    }

    @PostMapping("/dataGrid")
    @RequiresPermissions("/menu/dataGrid")
    @ResponseBody
    public ResultData menuDataGrid(Long current,Long pageSize,String searchCol,String searchValue){
        if(current == null || pageSize == null){
            return fail(ErrorCode.PAGE_PARAM_ERROR, ErrorMessage.PAGE_PARAM_ERROR);
        }
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        //目前的查询只有单表
        if(StringUtils.isNotBlank(searchValue) && StringUtils.isNotBlank(searchCol)){
            if(searchCol.equals(Constants.ID)){
                queryWrapper.eq("t.id",searchValue);
            }else{
                queryWrapper.like("t."+searchCol,searchValue);
            }
        }
        PageDataInfo<Map<String,Object>> pageDataInfo =new PageDataInfo<>();
        pageDataInfo.setCurrent(current);
        pageDataInfo.setSize(pageSize);
        menuService.selectMenuDataGrid(pageDataInfo,queryWrapper);
        return success(pageDataInfo);
    }

}